package com.pri.chat.application;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.Process;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebView;

import com.mob.MobSDK;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.api.UIKitOptions;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.util.NIMUtil;
import com.pri.chat.activity.vedio.widget.FileDownLoadUtil;
import com.pri.chat.bean.KeyAndValueEntity;
import com.pri.chat.database.greendao.GreenDaoManager;
import com.pri.chat.database.greendao.KeyAndValueEntityDao;
import com.pri.chat.nim.DemoCache;
import com.pri.chat.nim.NimSDKOptionConfig;
import com.pri.chat.nim.Preferences;
import com.pri.chat.nim.UserPreferences;
import com.pri.chat.nim.session.SessionHelper;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.shuyu.gsyvideoplayer.player.PlayerFactory;
import com.vondear.rxtool.RxTool;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.multidex.MultiDexApplication;
import tv.danmaku.ijk.media.exo2.Exo2PlayerManager;


/**
 * 描述：添加类的描述
 *
 * @author
 * @time 2018/10/15
 */
public class APP extends MultiDexApplication {
    private static APP applicationContext;
    private static List<Activity> activityList = new ArrayList<Activity>();

    static {//static 代码段可以防止内存泄露
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                return new MaterialHeader(context).setShowBezierWave(false);//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                layout.setEnableAutoLoadmore(true);
                return new ClassicsFooter(context).setSpinnerStyle(SpinnerStyle.Scale);
            }
        });
    }

    @Override
    public void onCreate() {
        super.onCreate();
        applicationContext = this;
        GreenDaoManager.getInstance();
        Log.i("time:APP",System.currentTimeMillis()+"");
        initThirdSDK();
    }

    private void initThirdSDK(){
        String path = Environment.getExternalStorageDirectory()+"/com.pri.chat/cache/video/";
        FileDownLoadUtil.getInstance().init(this,10, FileDownLoadUtil.Type.FIFO,path);
        RxTool.init(this);
        PlayerFactory.setPlayManager(Exo2PlayerManager.class);
        MobSDK.init(this);
        MobSDK.submitPolicyGrantResult(true, null);
        DemoCache.setContext(this);
        // 4.6.0 开始，第三方推送配置入口改为 SDKOption#mixPushConfig，旧版配置方式依旧支持。
        NIMClient.init(this, getLoginInfo(), NimSDKOptionConfig.getSDKOptions(this));
        // 以下逻辑只在主进程初始化时执行
        if (NIMUtil.isMainProcess(this)) {
            // 初始化UIKit模块
            initUIKit();
            // 初始化消息提醒
            NIMClient.toggleNotification(UserPreferences.getNotificationToggle());
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            WebView.setDataDirectorySuffix(Process.myPid() + "");
        }
    }

    private LoginInfo getLoginInfo() {
        String account = Preferences.getUserAccount();
        String token = Preferences.getUserToken();

        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(token)) {
            DemoCache.setAccount(account.toLowerCase());
            return new LoginInfo(account, token);
        } else {
            return null;
        }
    }
    private UIKitOptions buildUIKitOptions() {
        UIKitOptions options = new UIKitOptions();
        // 设置app图片/音频/日志等缓存目录
        options.appCacheDir = NimSDKOptionConfig.getAppCacheDir(this) + "/app";
        return options;
    }
    private void initUIKit() {
        // 初始化
        NimUIKit.init(this, buildUIKitOptions());
        // 设置地理位置提供者。如果需要发送地理位置消息，该参数必须提供。如果不需要，可以忽略。
//        NimUIKit.setLocationProvider(new NimDemoLocationProvider());
        // IM 会话窗口的定制初始化。
        SessionHelper.init();
        // 聊天室聊天窗口的定制初始化。
//        ChatRoomSessionHelper.init();

        // 通讯录列表定制初始化
//        ContactHelper.init();

        // 添加自定义推送文案以及选项，请开发者在各端（Android、IOS、PC、Web）消息发送时保持一致，以免出现通知不一致的情况
//        NimUIKit.setCustomPushContentProvider(new DemoPushContentProvider());
//
//        NimUIKit.setOnlineStateContentProvider(new DemoOnlineStateContentProvider());
    }

    public void exitApp() {
        for (Activity activity : activityList) {
            activity.finish();
        }
        /**
         * 清楚一些缓存
         */
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(1);
    }

    public void finishAllActivity() {
        for (Activity activity : activityList) {
            activity.finish();
        }
    }

    public void add(Activity activity) {
        activityList.add(activity);
    }
    public static APP getInstance() {
        return applicationContext;
    }

    public static KeyAndValueEntityDao getKeyAndValueEntityDao(){
        return GreenDaoManager.getInstance().getmDaoSession().getKeyAndValueEntityDao();
    }
}
